package demo1;

import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
import sun.security.krb5.internal.PAData;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Test_demo {
    static Jedis j=new Jedis("192.168.184.100",6379);
    @Test//常规操作
    public void m1(){
        System.out.println(j.ping());
        j.set("address","南京");
        System.out.println(j.get("address"));
        j.incr("age");
        j.incrBy("age",10);
        Set <String>keys=j.keys("*");
        for(String s:keys){
            System.out.println(s+",类型："+j.type(s));
        }

        Map<String,String> m=new HashMap<>();
        m.put("u1","11");
        m.put("u2","22");
        j.hmset("myCart",m);
        System.out.println(j.hgetAll("myCart"));
    }
    @Test
    public void t1(){
        Transaction t=j.multi();
        t.set("t1","tt1");
        t.set("t2","tt2");
        //t.discard();
        t.exec();
    }

    @Test
    public void t2() throws InterruptedException {
        j.set("money","960");//可用额度
        j.set("debt","40");//欠债
        int consume=10;//本次信用卡消费额度
        //添加watch锁
        j.watch("money");
        Thread.sleep(15000);
        int money=Integer.parseInt(j.get("money"));//
        if(money<consume){
            System.out.println("信用卡额度不够");
            return;
        }
        //开启事务:money-10,debt+10
        System.out.println("事务开启。。。");
        Transaction t=j.multi();
        t.incrBy("debt",consume);
        t.decrBy("money",consume);
        List list=t.exec();
        System.out.println(list);
        if(list==null){
            System.out.println("事务失败，请稍后再试");
        }
        System.out.println("事务执行结束，当前余额:" + j.get("money") + ",欠费:" + j.get("debt"));
    }

    //主从复制
    @Test
    public void master_slave(){
        Jedis master=new Jedis("192.168.184.100",6379);
        Jedis slave=new Jedis("192.168.184.100",6380);
        slave.slaveof("192.168.184.100",6379);//指定主服务器
        master.set("driver","com.mysql.driver");
        System.out.println(slave.get("driver"));
    }

}
